<template>
  <div class="roles">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-col :span="4">
          <el-button type="success" @click="goAddCate">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 表单区域 -->
      <zk-table
        :data="cateList"
        empty-text="暂无数据"
        :columns="columns"
        show-index
        index-text="#"
        :selection-type="false"
        :expand-type="false"
        border
      >
        <!-- 是否有效 -->
        <template slot="icon" slot-scope="scope">
          <i
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
            class="el-icon-success"
          ></i>
          <i v-else style="color: red" class="el-icon-error"></i>
        </template>

        <!-- 排序 -->
        <template slot="sort" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level == 0" type="success" size="small"
            >一级</el-tag
          >
          <el-tag
            v-else-if="scope.row.cat_level == 1"
            type="warning"
            size="small"
            >二级</el-tag
          >
          <el-tag
            v-else-if="scope.row.cat_level == 2"
            type="danger"
            size="small"
            >三级</el-tag
          >
        </template>

        <!-- 操作 -->
        <template slot="oper" slot-scope="scope">
          <el-button
            type="success"
            icon="el-icon-edit"
            plain
            size="small"
            @click="editCate(scope.row)"
            >设置</el-button
          >

          <el-button
            type="danger"
            icon="el-icon-delete"
            plain
            size="small"
            @click="delCate(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </zk-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加分类对话框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="cateFormVisible"
        width="50%"
        @close="closeAddCate('addCateRef')"
      >
        <el-form :model="addCateInfo" ref="addCateRef">
          <el-form-item
            label="分类名称"
            label-width="80px"
            prop="cat_name"
            :rules="[{ required: true, message: '分类名称不能为空' }]"
          >
            <el-input
              v-model="addCateInfo.cat_name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <!-- 级联选择器 -->
          <el-form-item label="父级分类" label-width="80px">
            <el-cascader
              v-model="selectedkeys"
              :options="parentCateList"
              :props="{
                expandTrigger: 'hover',
                ...propsParent,
                checkStrictly: 'true',
              }"
              @change="handleCascader"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cateFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureAddCate('addCateRef')"
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <!-- 编辑分类对话框 -->
      <el-dialog title="编辑分类" :visible.sync="editCateVisible" @close="closeEditCate('editCateRef')">
        <el-form :model="editCateInfo" ref="editCateRef">
          <el-form-item label="活动名称" label-width="80px" prop="cat_name" :rules="[{ required: true, message: '分类名称不能为空' }]">
            <el-input v-model="editCateInfo.cat_name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editCateVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureEditCate('editCateRef')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

export default {
  data() {
    return {
      // 商品分类数据列表
      cateList: [],
      // 获取分类数据列表 请求参数
      queryInfo: {
        type: 3,
        pagenum: 1, // 当前页码值
        pagesize: 5, // 每页显示多少条数据
      },
      // 分类数据列表 总数
      total: 0,
      // 添加分类对话框
      cateFormVisible: false,
      // 编辑分类对话框
      editCateVisible:false,
      // 添加分类 请求参数
      addCateInfo: {
        cat_pid: 0,
        cat_name: "",
        cat_level: 0,
      },
      editCateInfo:{
        cat_id:'',
        cat_name:''
      },
      // tree-table 列表
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
          minWidth: "130px",
        },
        {
          label: "是否有效",
          type: "template",
          template: "icon",
        },
        {
          label: "排序",
          type: "template",
          template: "sort",
        },
        {
          label: "操作",
          align: "center",
          type: "template",
          template: "oper",
          minWidth: "200px",
        },
      ],
      // 添加分类 级联选择器 数据列表
      parentCateList: [],
      // 添加分类 级联选择器 选择值
      selectedkeys: [],
      // 添加分类 级联选择器 展示项
      propsParent: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    // 获取分类数据列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryInfo,
      });
      // console.log(res.data);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.total = res.data.total;
      this.cateList = res.data.result;
    },
    // 获取父级分类列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      // console.log(res,111);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.parentCateList = res.data;
    },
    // 编辑分类
    editCate(info) {
      this.editCateInfo.cat_id = info.cat_id;
      this.editCateInfo.cat_name = info.cat_name;
      this.editCateVisible = true;
    },
    // 编辑分类对话框 关闭
    closeEditCate(refname) {
      this.$refs[refname].resetFields();
    },
    // 编辑分类对话框 确定按钮
    sureEditCate(refname) {
      this.$refs[refname].validate(async valid => {
        if(!valid) return 
        const {data:res} =await this.$http.put(`categories/${this.editCateInfo.cat_id}`,this.editCateInfo);
        //  console.log(res);
        if(res.meta.status !== 200) return this.$message.error('更新分类失败')
        this.getCateList();
        this.editCateVisible = false;
        this.$message.success('分类更新成功!!!');
      })
      
    },
    // 删除分类
    async delCate(id) {
      const context = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err);
        // console.log(context);
        if(context !== 'confirm') return 
        const {data:res} = await this.$http.delete(`categories/${id}`);
        // console.log(res);
        if(res.meta.status !== 200) return this.$message.error('删除分类失败');
        this.getCateList();
        this.$message({
          type: 'success',
          message: '成功删除分类!!!'
        });
    },
    // 分页 每页展示几条数据
    handleSizeChange(size) {
      this.queryInfo.pagesize = size;
      this.getCateList();
    },
    // 分页 当前页
    handleCurrentChange(cur) {
      this.queryInfo.pagenum = cur;
      this.getCateList();
    },
    // 监听级联选择器值的变化
    handleCascader(val) {
      const len = val.length;
      if (len > 0) {
        this.addCateInfo.cat_pid = val[len - 1];
        this.addCateInfo.cat_level = len;
      } else {
        this.addCateInfo.cat_pid = 0;
        this.addCateInfo.cat_level = 0;
      }
    },
    // 添加分类 按钮
    goAddCate() {
      this.cateFormVisible = true;
      this.getParentCateList();
    },
    // 关闭添加分类对话框
    closeAddCate(refname) {
      this.$refs[refname].resetFields();
      this.selectedkeys = [];
      this.addCateInfo.cat_pid = 0;
      this.addCateInfo.cat_level = 0;
    },
    // 添加分类对话框 确定按钮
    sureAddCate(refname) {
      this.$refs[refname].validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateInfo
        );
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error("添加分类失败");
        this.getCateList();
        this.cateFormVisible = false;
        this.$message.success("添加分类成功!!!");
      });
    },
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-cascader {
  width: 100%;
}
</style>